using Gameplay.PVE.Entity;
using Gameplay.PVE.Utils;
using UnityEngine;

namespace Gameplay.PVE
{
    public class EnemyRangeMoveBehaviour : EnemyMoveBehaviour
    {
        private bool firstSearchInGame;
        protected override void UpdateGame()
        {
            base.UpdateGame();
            UpdateEnemyAttackPoint();
        }
        
        public override void Init(UnitBase unit, UnitRoadPath roadPath)
        {
            firstSearchInGame = true;
            base.Init(unit, roadPath);
            if (roadPath is AStarRoadPath path)
            {
                path.SetCondition2Handler(() =>
                {
                    if (!unit.Data.IsInScreen())
                    {
                        return false;
                    }
                    else if (unit.Data.attackPosition != Vector3.zero)
                    {
                        var d = Vector3.Distance(unit.Data.attackPosition, unit.Data.position);
                        return d < unit.Data.configMoveSpeed * TimeManager.LogicDeltaTime;
                    }
                    else if (unit.Data.lockTarget == null || unit.Data.lockTarget.Data.isDead)
                    {
                        return false;
                    }
                    return unit.Data.IsAttackInRange(1);
                });
                path.SetForceEndCondition(() => { return unit.Data.attackPosition != Vector3.zero; });
            }
        }
        
        private void UpdateEnemyAttackPoint()
        {
            if (unit.Data.IsInSkill() || unit.Data.IsInAttack())
            {
                firstSearchInGame = false;
                return;
            }
            
            unit.Data.moveState = 2;
            if (unit.Data.modelId == PveGlobalVlues.HelicopterModelId)
            {
                unit.Data.attackPosition = Vector3.zero;
            }
            else if (!unit.Data.IsInScreen())
            {
                unit.Data.attackPosition = Vector3.zero;
            }
            else if (unit.Data.lockTarget != null) // && Vector3.Distance(unit.Data.position,unit.Data.lockTarget.Data.position) > unit.Data.attackRange)
            {
                if (firstSearchInGame)
                {
                    
                }
                else
                {
                    unit.Data.attackPosition = Vector3.zero;
                }
            }

            if (unit.Data.lockTarget != null && (unit.Data.attackPosition != unit.Data.position || !unit.Data.IsInScreen()))
            {
                
            }
            else
            {
                unit.Data.moveState = 0;
                unit.Data.manualForward = Vector3.zero;
            }


            if (unit.Data.attackPosition != Vector3.zero && !unit.Data.hasReachAttackPosition)
            {
                unit.Data.SetTargetPosition(unit.Data.attackPosition);
            }
        }
    }
}